import {executeCommand} from "./ipc";
import {basename, dirname} from "@tauri-apps/api/path";

export async function openFileFolder(filePath: string): Promise<void> {
  await executeCommand('explorer', [`/select,${filePath}`]);
}

export async function replaceContent(
  filePath: string,
  searchValue: string | RegExp,
  replaceValue: string,
  encoding: string = 'gbk'
): Promise<void> {
  const dir = await dirname(filePath);
  const filename = await basename(filePath)
  let content = await executeCommand("powershell" , ["-Command", `(Get-Content "${filename}")`], dir, encoding);

  if (!content) {
    console.log(`File ${filename} is empty or does not exist`);
    return;
  }

  const hasMatch = typeof searchValue === "string"
    ? content.includes(searchValue)
    : searchValue.test(content);
  if (!hasMatch) {
    console.log(`No match found for ${searchValue} in ${filename}`);
    return;
  }

  const regex = searchValue instanceof RegExp? searchValue.source : searchValue;
  const powershellCmd = `(Get-Content "${filename}") -replace "${regex}", "${replaceValue}" | Set-Content "${filename}"`;
  await executeCommand("powershell", ["-Command", powershellCmd], dir, encoding);
}


export async function getContent(
  filePath: string,
  encoding: string = 'gbk'
): Promise<string> {
  const dir = await dirname(filePath);
  const filename = await basename(filePath)
  const content = await executeCommand("powershell" , ["-Command", `(Get-Content "${filename}")`], dir, encoding);
  if (!content) {
    return '';
  }
  return content;
}
